import { login, logout, getUserInfo } from '@/api/user'
import { setToken, getToken } from '@/libs/util'

export default {
	state: {
		userName: '',
		userId: '',
		bid: '',
		avatorImgPath: '',
		token: '',
		rc_token: '',
    user_type: '', // 10 : 管理员
		access: '',
		type: '',
	},
	mutations: {
		setAvator(state, avatorPath) {
			state.avatorImgPath = avatorPath
		},
		setUserId(state, id) {
			state.userId = id
		},
		setBid(state, bid) {
			state.bid = bid
		},
		setUserName(state, name) {
			state.userName = name
		},
		setAccess(state, access) {
			state.access = access
		},
		setRcToken(state, rc_token) {
			state.rc_token = rc_token
		},
		setToken(state, token) {
			state.token = token
			setToken(token)
		},
    setType(state, type) {
    	state.type = type
    },
    setRole(state, role) {
    	state.role = role
    },
    setFirstAccess(state, first_access) {
    	state.first_access = first_access
    }
	},
	actions: {
		// 登录
		handleLogin({ commit }, { userName, password }) {
			userName = userName.trim()
			return new Promise((resolve, reject) => {
				login({
					userName,
					password,
				})
					.then(res => {
						if (res.code == 0) {
							commit('setToken', res.Authorization)
						}
						resolve(res)
					})
					.catch(err => {
						reject(err)
					})
			})
		},
		// 退出登录
		handleLogOut({ state, commit }) {
			return new Promise((resolve, reject) => {
				commit('setToken', '')
				commit('setUserName', '')
				localStorage.removeItem("user")
				//localStorage.clear()
				resolve()
				// 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
				// commit('setToken', '')
				// commit('setAccess', [])
				// resolve()
			})
		},
		// 获取用户相关信息
		getUserInfo({ state, commit }) {
			return new Promise((resolve, reject) => {
				getUserInfo(state.token)
					.then(res => {
						const data = res.data
						commit('setAvator', data.avator)
						commit('setUserName', data.user_name)
						commit('setUserId', data.user_id)
						commit('setAccess', data.access)
						resolve(data)
					})
					.catch(err => {
						reject(err)
					})
			})
		},
	},
}
